package com.steven.door.services;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.service.autofill.FillEventHistory;
import android.util.Log;

import com.steven.door.base.Constant;
import com.steven.door.receiver.WEBReceive;
import com.steven.door.utils.MacUtils;
import com.steven.door.utils.NetCheckUtil;
import com.steven.door.utils.SPUtils;
import com.steven.door.utils.ToastUtils;
import com.steven.door.webSocket.ConnectStatus;
import com.steven.door.webSocket.WebSocketCallBack;
import com.steven.door.webSocket.WebSocketHandler;

import java.util.Objects;


/**
 * 处理webSocket一些事情  不需要和activity交互
 */
public class WebSocketService extends Service {
    private static String TAG = WebSocketService.class.getSimpleName();
    private static WebSocketHandler webSocketHandler;
    private static MyHandler myHandler;
    private Context mContext;
    private Intent it;
    private static String mac;
    private int connectCount = 0;

    @Override
    public void onCreate() {//启动只调用一次
        super.onCreate();
        it = new Intent(this, WEBReceive.class);
        mContext = this;
        myHandler = new MyHandler();
        webSocketHandler = WebSocketHandler.getInstance(Constant.wsUrl);
    }

    @Override
    public void onDestroy() {//只会走一次
        super.onDestroy();
        if (myHandler != null) {
            myHandler.removeMessages(0);
            myHandler = null;
        }
        if (webSocketHandler != null) {
            if (webSocketHandler.getStatus() == ConnectStatus.Open) {
                webSocketHandler.close();
                webSocketHandler.removeSocketIOCallBack();
                webSocketHandler = null;
            }
        }
    }

    @Override
    public int onStartCommand(final Intent intent, int flags, int startId) {
        mac = MacUtils.getMac(mContext).replace(":", "-");
//        mac="20-72-0D-39-2C-C2";
        SPUtils.put(this, "mac", mac);//存储 mac
        //每次启动都会走这个方法
        if (webSocketHandler.getStatus()!=null){
            if (!"Open".equals(webSocketHandler.getStatus().toString()) ){
                webSocketHandler.connect();
                webSocketHandler.setSocketIOCallBack(new WebSocketCallBack() {
                    @Override
                    public void onOpen() {//连接成功
                        connectCount = 0;
                        Log.e(TAG, "onOpen: " + mac  );
                        webSocketHandler.send("bind{\"uid\":\"" + mac + "\"}");//上报唯一标识  表示设备已经注册
//                sendHeartBeat();//通过闹钟定时器 实现发送心跳包
                        myHandler.sendEmptyMessageDelayed(0, Constant.heartTime);//10秒发送一次
                    }

                    @Override
                    public void onMessage(String data) {//接收到消息
                        Log.e(TAG, "onMessage: " + data);
                        it.putExtra("type", Constant.server);
                        it.putExtra("data", data);
                        mContext.sendBroadcast(it);
                    }

                    @Override
                    public void onClose() {//连接断开
                        Log.e(TAG, "onClose: 链接断开");
                    }

                    @Override
                    public void onConnectError(Throwable t) {//连接失败 或 超时

                        if (NetCheckUtil.checkNet(mContext)) {//表示 有网  进行
                            connectCount++;
                            if (connectCount <= 5) {
                                webSocketHandler.reConnect();
                            } else {
                                //连接次数 有限 超过5次
                                myHandler.removeMessages(0);
                            }

                        } else {//表示  没网
                            myHandler.removeMessages(0);
                            it.putExtra("type", Constant.net);
                            mContext.sendBroadcast(it);
                        }

                    }
                });
            }

        }else {
            webSocketHandler.connect();
            webSocketHandler.setSocketIOCallBack(new WebSocketCallBack() {
                @Override
                public void onOpen() {//连接成功
                    connectCount = 0;
                    Log.e(TAG, "onOpen: " + mac  );
                    webSocketHandler.send("bind{\"uid\":\"" + mac + "\"}");//上报唯一标识  表示设备已经注册
//                sendHeartBeat();//通过闹钟定时器 实现发送心跳包
                    myHandler.sendEmptyMessageDelayed(0, Constant.heartTime);//10秒发送一次
                }

                @Override
                public void onMessage(String data) {//接收到消息
                    Log.e(TAG, "onMessage: " + data);
                    it.putExtra("type", Constant.server);
                    it.putExtra("data", data);
                    mContext.sendBroadcast(it);
                }

                @Override
                public void onClose() {//连接断开
                    Log.e(TAG, "onClose: 链接断开");
                }

                @Override
                public void onConnectError(Throwable t) {//连接失败 或 超时
                    myHandler.removeMessages(0);
                    Log.e(TAG, "onConnectError: 链接断开！" );
                    if (NetCheckUtil.checkNet(mContext)) {//表示 有网  进行
                        connectCount++;
                        if (connectCount <= 5) {
                            webSocketHandler.reConnect();
                        } else {
                            //连接次数 有限 超过5次
                            myHandler.removeMessages(0);
                        }

                    } else {//表示  没网
                        myHandler.removeMessages(0);
                        it.putExtra("type", Constant.net);
                        mContext.sendBroadcast(it);
                    }

                }
            });
        }

        return super.onStartCommand(intent, flags, startId);
    }

    @SuppressLint("HandlerLeak")
    private static class MyHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Log.e(TAG, "handleMessage: 发送心跳包!");
            webSocketHandler.send("login{\"uid\":\"" + mac + "\"}");
            myHandler.sendEmptyMessageDelayed(0, Constant.heartTime);
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Not yet implemented");
    }

}
